package com.rjwh.dingdong.client.activity.more;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aishua.lib.utils.AsAppUtils;
import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.image.ImageListBrowseActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.MorePersonDataPresenter;
import com.rjwh.dingdong.client.mvp.view.MorePersonDataView;
import com.rjwh.dingdong.client.util.BitmapFileUtil;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.Photo;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.ToastUtil;
import com.rjwh.dingdong.client.view.PhotoDialog;
import com.rjwh.dingdong.client.widget.RoundImageView;
import com.tbruyelle.rxpermissions.RxPermissions;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * @author Kay
 * @ClassName MorePersonDataActivity
 * @Description 个人中心->个人资料
 * @date 2016-7-13
 * @history 2016-7-13 author: description:
 */
public class MorePersonDataActivity extends BaseActivity implements MorePersonDataView {
    private static final int PICTAKEPHOTO = 1;
    private static final int PICINTUKU = 2;
    private static final int PHOTO_CUT = 3;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.community_post_publish_center_tv)
    TextView communityPostPublishCenterTv;
    @BindView(R.id.person_data_head_img)
    RoundImageView personDataHeadImg;
    @BindView(R.id.person_data_phone_tv)
    TextView personDataPhoneTv;
    @BindView(R.id.person_data_nick_name_tv)
    TextView personDataNickNameTv;
    private String cutImgPath;
    private String nameInput;
    private PhotoDialog photoDialog;

    private MorePersonDataPresenter presenter;
    private Uri uritempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.more_person_data_layout);
        ButterKnife.bind(this);
        initView();
        presenter = new MorePersonDataPresenter(this, this);
    }

    private void initView() {
        initToolbarHelper();
        Glide.with(this).load(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERIMAGE)).dontAnimate().placeholder(R.drawable.icon_defult_avatar).error(R.drawable.icon_defult_avatar).into(personDataHeadImg);
        personDataNickNameTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERNAME));
        personDataPhoneTv.setText(MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERPHONE));

        photoDialog = new PhotoDialog(this);
        photoDialog.setBackLsn(new PhotoDialog.onBackLsn() {
            @Override
            public void onClick(int type) {
                if (type == 0) {
                    Photo.systemPhotoAlbum(MorePersonDataActivity.this, PICINTUKU);
                } else {
                    RxPermissions.getInstance(getBaseContext())
                            .request(Manifest.permission.CAMERA)
                            .subscribe(new Action1<Boolean>() {
                                @Override
                                public void call(Boolean aBoolean) {
                                    LogUtil.d("获取到了运行权限:" + aBoolean);
                                    if (aBoolean) {
                                        cutImgPath = FileUtils.getTempImageStorageDirectory() + System
                                                .currentTimeMillis() + ".png";
                                        Photo.startComer(MorePersonDataActivity.this, PICTAKEPHOTO,
                                                Uri.fromFile(new File(cutImgPath)));
                                    }
                                }
                            }, new Action1<Throwable>() {
                                @Override
                                public void call(Throwable throwable) {
                                    LogUtil.d("获取权限失败", throwable.getMessage());
                                }
                            });
                }
            }
        });

    }

    private void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(getResources().getString(R.string.more_person_data));
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @OnClick({R.id.person_data_head_img_root_rl, R.id.person_data_nick_name_root, R.id.person_data_head_img, R.id.more_baby_info_root})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.person_data_head_img_root_rl:
                photoDialog.show();
                break;
            case R.id.person_data_nick_name_root:
                showNicknameDailog();
                break;
            case R.id.person_data_head_img:
                showAvatar();
                break;
            case R.id.more_baby_info_root:
                startActivity(new Intent(this, MoreBabyInfoActivity.class));
                break;
        }
    }

    /**
     * 显示头像大图
     */
    private void showAvatar() {
        ArrayList<String> listImage = new ArrayList<>();
        String avatar = MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_USERIMAGE);
        String bigAvatar = avatar.replace("/bp/", "/mp/");
        listImage.add(bigAvatar);
        Intent intentBrowse = new Intent(this, ImageListBrowseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("list", listImage);
        bundle.putBoolean("isAvatar", true);
        intentBrowse.putExtras(bundle);
        intentBrowse.putExtra("position", 0);
        startActivity(intentBrowse);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICTAKEPHOTO:
                //拍照
                if (resultCode == RESULT_OK) {
                    if (AsAppUtils.hasSdcard()
                            && !AsStrUtils.isEmpty(cutImgPath)) {
                        File tempFile = new File(cutImgPath);
                        if (!tempFile.exists()) {
                            showToast("图片不存在！");
                            return;
                        }
                        LogUtil.d("cutImgPath:" + cutImgPath);
                        Uri uri = Uri.fromFile(tempFile);
                        startPhotoZoom(uri);
//                        uploadUserImage(cutImgPath);
                    } else {
                        showToast("未找到存储卡，无法存储照片！");
                    }
                }
                break;
            case PICINTUKU:
                //相册
                if (data != null) {
                    LogUtil.d("data:" + data);
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    if (uri != null) {
                        LogUtil.d("uri:" + uri);
                        startPhotoZoom(uri);
//                        uploadUserImage(Photo.getPhotoPic(this, uri));
                    }
                }
                break;
            case PHOTO_CUT:
                //裁剪
                if (uritempFile != null) {
                    saveCropImage(uritempFile);
                }
                break;
        }
    }

    /**
     * 处理裁剪后的图片
     *
     * @param picUri
     */
    private void saveCropImage(Uri picUri) {
        Bitmap cropBitmap = BitmapFileUtil.getBitmapFromUri(picUri, MorePersonDataActivity.this);
        if (cropBitmap != null) {
            String urlpath = BitmapFileUtil.saveBitmap(cropBitmap);
            uploadUserImage(urlpath);
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        int dp = 500;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);//输出是X方向的比例
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
        intent.putExtra("outputX", dp);//输出X方向的像素
        intent.putExtra("outputY", dp);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        //uritempFile为Uri类变量，实例化uritempFile
        String uriString = FileUtils.getTempImageStorageDirectory() + System
                .currentTimeMillis() + ".png";
        uritempFile = Uri.fromFile(new File(uriString));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("return-data", false);//设置为不返回数据 防止数据太大闪退
        startActivityForResult(intent, PHOTO_CUT);
    }

    /**
     * 上传头像
     *
     * @param cutImgPath
     */
    public void uploadUserImage(final String cutImgPath) {
        showLoadDialog();
        final AjaxParams ps = new AjaxParams();
        ps.put("avatartype", "1");
        String outFile = FileUtils.getTempImageStorageDirectory() + System.currentTimeMillis() + ".png";
        try {
            File file = BitmapFileUtil.compressBmpToFile(90, cutImgPath, outFile);
            if (file != null) {
                ps.put("img", file);
            } else {
                ToastUtil.showToast(MorePersonDataActivity.this, "图片路径错误");
            }
            LogUtil.e("MorePersonDataActivity", "img: " + file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        MyApplication.http.post(LocalConstant.SEND_UPLOAD_USERIMAGE, ps,
                new AjaxCallBack<String>() {
                    @Override
                    public void onSuccess(String t) {
                        super.onSuccess(t);
                        dismissLoadDialog();
                        LogUtil.e("MorePersonDataActivity", "onSuccess: " + t);
                        try {
                            JSONObject jb = new JSONObject(t);
                            JSONObject exeustate = jb
                                    .getJSONObject("exeustate");
                            String state = exeustate.getString("state");
                            String msg = exeustate.getString("msg");
                            if (!AsStrUtils.isEmpty(state) && state.equals("1") && !AsStrUtils.isEmpty(msg)) {
                                LogUtil.d("msg: " + msg);
                                MyApplication.spUtil.setStrPreference(MyApplication.getInstance(), LocalConstant.SP_USERIMAGE, msg);
                                Glide.with(MorePersonDataActivity.this).load(msg).dontAnimate().placeholder(R.drawable.icon_defult_avatar).error(R.drawable.icon_defult_avatar).into(personDataHeadImg);
                                RxBus.get().post(LocalConstant.RX__POST_LOGIN_UPDATE_UI, 1);
                                ToastUtil.showToast(MorePersonDataActivity.this, "修改成功");
                            } else {
                                ToastUtil.showToast(MorePersonDataActivity.this, "上传失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showToast(MorePersonDataActivity.this, "上传失败");
                        }
                    }

                    @Override
                    public void onFailure(Throwable t, String strMsg) {
                        super.onFailure(t, strMsg);
                        LogUtil.d("MorePersonDataActivity", "onFailure: " + strMsg);
                        dismissLoadDialog();
                        ToastUtil.showToast(MorePersonDataActivity.this, "网络异常");
                    }
                });
    }

    private void showNicknameDailog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        alertDialog.setView(inflater.inflate(R.layout.dialog_person_data_nick_name, null));
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_person_data_nick_name);
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        final EditText nick_name_et = (EditText) window.findViewById(R.id.dialog_person_data_nick_name_et);
        Button nick_name_conform_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_conform_btn);
        Button nick_name_cancel_btn = (Button) window.findViewById(R.id.dialog_person_data_nick_name_cancel_btn);
        nick_name_et.setText(personDataNickNameTv.getText().toString());
        nick_name_conform_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                nameInput = nick_name_et.getText().toString();
                if (AsStrUtils.isEmpty(nameInput)) {
                    ToastUtil.showToast(MorePersonDataActivity.this, "您还没有输入内容");
                    return;
                }
                showLoadDialog();
                // 调用修改昵称接口
                presenter.saveUserData(nameInput, "1");
            }
        });
        nick_name_cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

    }

    @Override
    public void showLoading() {
        showLoadDialog();
    }

    @Override
    public void dismissLoading() {
        dismissLoadDialog();
    }

    @Override
    public void updataData() {
        personDataNickNameTv.setText(nameInput);
        MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_USERNAME, nameInput);
        RxBus.get().post(LocalConstant.RX__POST_LOGIN_UPDATE_UI, 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }
}
